﻿using Abp.Domain.Entities;
using Abp.Domain.Repositories;
using Batman.Core;
using Batman.Jianbei.Forum.Repositories.Mongo;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Batman.Jianbei.Forum.Core.ChatRoom
{
    /// <summary>
    /// 聊天动作
    /// </summary>
    public class ChatAction : Entity<string>
    {
        /// <summary>
        /// 发送操作的人
        /// </summary>
        public string Uid { get; set; }

        /// <summary>
        /// 发生动作时间
        /// </summary>
        public DateTime CreateAt { get; set; }

        /// <summary>
        /// 聊天动作
        /// </summary>
        public ChatActionEnum Action { get; set; }

        /// <summary>
        /// 聊天动作
        /// </summary>
        public string ActionName { get { return Action.ToString(); } set { } }

        /// <summary>
        /// 房间编号
        /// </summary>
        public string RoomId { get; set; }

        /// <summary>
        /// 被执行用户（可空）
        /// </summary>
        public string RelateUId { get; set; }


        public ChatAction()
        {
            CreateAt = DateTime.Now;
        }

        public ChatAction(string uid, ChatActionEnum action, string roomId, string relateUId = null) : this()
        {
            CreateAt = DateTime.Now;
            Action = action;
            Uid = uid;
            RoomId = roomId;
            RelateUId = relateUId;
        }

        #region 充血方法

        /// <summary>
        /// 是否已在房间
        /// </summary>
        /// <param name="dbCollection"></param>
        /// <param name="uid">判断的用户ID</param>
        /// <param name="roomId">房间号</param>
        /// <returns></returns>
        public static bool IsInRoom(IRepository<ChatAction, string> repo, string uid, string roomId)
        {
            // 只查询两种动作
            var actions = new List<ChatActionEnum> { ChatActionEnum.进入房间, ChatActionEnum.离开房间 };

            var data = repo.GetQuery().Where(t => t.RoomId == roomId && t.Uid == uid && actions.Contains(t.Action));
            var last = data.OrderByDescending(t => t.CreateAt).FirstOrDefault();

            // 最后一条数据如果是空或者是离开房间动作 则表示不在房间种
            if (last == null || last.Action == ChatActionEnum.离开房间)
                return false;

            return true;
        }

        /// <summary>
        /// 写入到数据库
        /// </summary>
        /// <param name="dbCollection"></param>
        /// <param name="action"></param>
        public void Add2db(MongoRepositoryBase<ChatAction> dbCollection)
        {
            dbCollection.Insert(this);
        }

        #endregion
    }
}
